package com.colouredglaze.controller;

import com.colouredglaze.entity.TbGoods;
import com.colouredglaze.entity.TbUser;
import com.colouredglaze.service.GoodsService;
import com.colouredglaze.service.UserService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;

import static com.colouredglaze.utils.AliyunSms.sendSmsUtil;

/**
 * @author ZhangLin
 * @version 1.0
 * @date 2020/11/24 18:58
 */
@Controller
@RequestMapping("/")
@RequiredArgsConstructor
@Api(description = "用户控制器")
public class UserController {

    private final  UserService userService;

    private final  GoodsService goodsService;

    private List<TbGoods> goodsList;

    @RequestMapping("for")
    public ModelAndView index() {
        goodsList = goodsService.selectList();
        return new ModelAndView("/user/index", "goodsList", goodsList);
    }

    @RequestMapping("forA")
    public ModelAndView goodsA() {
        goodsList = goodsService.selectList();
        return new ModelAndView("/user/shop-grid-full-width", "goodsList", goodsList);
    }

    //更新个人信息
    @RequestMapping("updateUser")
    public ModelAndView updateUser(String p_password, String n_password, String uname, HttpServletRequest request) {
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        String uid = user.getUid();
        if (uname != null && n_password == null) {
            TbUser tbUser = TbUser.QueryBuild().uid(uid).uname(uname);
            int i = userService.updateUser(tbUser);
            return new ModelAndView("redirect:/userInfo");
        } else if (uname == null && n_password != null) {
            TbUser tbUser = TbUser.QueryBuild().uid(uid).password(p_password);
            TbUser tmpUser = userService.selectOne(tbUser);
            if (tmpUser == null) {
                if (user.getRole() == 0) {
                    return new ModelAndView("/user/user", "msg", "原密码输入错误");
                } else {
                    return new ModelAndView("/admin/password-change", "msg", "原密码输入错误");
                }

            } else {
                TbUser tbUser1 = TbUser.QueryBuild().uid(uid).password(n_password);
                int i = userService.updateUser(tbUser1);
                return new ModelAndView("/login", "msg", "修改成功，请重新登录");
            }
        }
        return new ModelAndView("redirect:/userInfo");
    }

    //查询个人信息
    @RequestMapping("userInfo")
    public ModelAndView selectUser(HttpServletRequest request) {
        TbUser user = (TbUser) request.getSession().getAttribute("user");
        String uid = user.getUid();
        TbUser tbUser = TbUser.QueryBuild().uid(uid);
        TbUser reUser = userService.selectOne(tbUser);
        if (user.getRole() == 0) {
            return new ModelAndView("/user/user", "reUser", reUser);
        } else {
            return new ModelAndView("/admin/password-change", "reUser", reUser);
        }
    }

    @RequestMapping(value = "login.do", method = RequestMethod.GET)
    public ModelAndView login() {
        return new ModelAndView("login");
    }

    //登录检测
    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    public ModelAndView loginSubmit(String uid, String password, HttpServletRequest request) {
        TbUser user = TbUser.QueryBuild().uid(uid).password(password);
        TbUser userTmp = userService.selectOne(user);
        if (userTmp != null) {
            request.getSession().setAttribute("user", userTmp);
            if (userTmp.getRole().equals(1)) {
                return new ModelAndView("redirect:/jsp/admin/index.jsp");
            } else if (userTmp.getRole().equals(0)) {
                return new ModelAndView("redirect:/for");
            } else {
                return new ModelAndView("login", "msg", "用户名或密码错误");
            }
        } else {
            return new ModelAndView("login", "msg", "用户名或密码错误");
        }
    }

    @RequestMapping(value = "register.do", method = RequestMethod.GET)
    public ModelAndView register() {
        return new ModelAndView("login");
    }

    //注册信息
    @RequestMapping(value = "register.do", method = RequestMethod.POST)
    public ModelAndView registerSubmit(HttpServletRequest request, String uid, String uname, String password, String verifyCode) {
        try {
            String Code = (String) request.getSession().getAttribute("verifyCode");
            Long createTime = (Long) request.getSession().getAttribute("createTime");
            if (!Code.equals(verifyCode)) {
                return new ModelAndView("register", "msg", "验证码错误");
            }
            if ((System.currentTimeMillis() - createTime > 1000 * 60 * 5)) {
                return new ModelAndView("register", "msg", "验证码已过期");
            }
        } catch (Exception e) {
            return new ModelAndView("register", "msg", "请获取验证码");
        }
        TbUser user = TbUser.QueryBuild().uid(uid).password(password).uname(uname).role(0);
        try {
            int fl = userService.insertOne(user);
            if (fl == 1) {
                return new ModelAndView("login", "msg", "注册成功，请登录");
            }
        } catch (Exception e) {
            return new ModelAndView("register", "msg", "注册失败");
        }
        return new ModelAndView("register", "msg", "注册失败");
    }

    //短信验证码
    @RequestMapping(value = "sendSms", method = RequestMethod.POST)
    @ResponseBody
    public String sendSms(HttpServletRequest request, String uid) {
        try {
            JSONObject json = null;
            //生成6位验证码
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
            //发送短信
            json = sendSmsUtil(uid, verifyCode);
            assert json != null;
            if (json.get("Code").equals("OK")) {
                request.getSession().setAttribute("verifyCode", verifyCode);
                request.getSession().setAttribute("createTime", System.currentTimeMillis());
                return "success";
            } else {
                return "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("logout.do")
    public ModelAndView logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return new ModelAndView("redirect:/login.do");
    }

}
